<?php
/**
 * Holds class Mvc_View_JSONedSmarty
 *
 * @author daantimmer
 *
 * @package Library
 * @subpackage Mvc
 */

/**
 * A view that uses both JSON and Smarty to output data as JSON.
 *
 * This view first uses Smarty to parse data located in APP/tpljs/$module/src/$controller/$action.js
 * These views are assumed to return valid javascript data.
 *
 * @author daantimmer
 */
class Mvc_View_JSONedSmarty extends Mvc_View{
	
	/**
	 * @see Mvc_View_Interface::render()
	 */
	public function render(){
		$smarty = new Smarty();
		
		$module = $this->_module;
		$controller = strtolower(substr($this->_controller,0,strlen($this->_controller) - strlen('Controller')));
		$action = strtolower(substr($this->_action,strlen('action')));
		
		$dir = APP . 'tpljs' . DIRECTORY_SEPARATOR . strtolower($module) . DIRECTORY_SEPARATOR;
		
		$compiledir = $dir . 'bin';
		$cachedir	= $dir . 'cache';
		$srcdir		= $dir . 'src';
		
		$ctrldir	= $srcdir . DIRECTORY_SEPARATOR . $controller;
		
		if(	$this->chkDir($dir) &&
			$this->chkDir($compiledir) &&
			$this->chkDir($cachedir) &&
			$this->chkDir($srcdir) &&
			$this->chkDir($ctrldir)){
			
			$smarty->compile_dir = $compiledir;
			$smarty->cache_dir = $cachedir;
			$smarty->template_dir = $srcdir;
			
//			$page = $controller . DIRECTORY_SEPARATOR . $action . '.html';
			$views = APP . 'views' . DIRECTORY_SEPARATOR . $module;
//
//			$smarty->assign("page",$page);
			$smarty->assign("views",$views);
//
			foreach($this->_var as $key => $var)
				$smarty->assign($key,$var);
			
			$smarty->left_delimiter = '<{';
			$smarty->right_delimiter = '}>';
			
			return $smarty->fetch($ctrldir . DIRECTORY_SEPARATOR . $action . '.js');
		}
		return "";
	}
	
	public function chkDir($dir,$mode = 0x1FF){
		$bool = true;
		if(!is_dir($dir)){
	 		$bool = mkdir($dir,$mode,true);
			if($bool)chmod($dir,$mode);
		}
		return $bool;
	}
}